package com.javaeedev.lightweight.mvc.sample.web;

import java.util.HashMap;
import java.util.Map;

import com.javaeedev.lightweight.mvc.ActionContext;
import com.javaeedev.lightweight.mvc.ModelAndView;
import com.javaeedev.lightweight.mvc.sample.User;

/**
 * Process user sign on.
 * 
 * @author Xuefeng
 */
public class SignonAction extends AbstractAction {

    private String username;
    private String password;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public ModelAndView execute() throws Exception {
        username = username.trim().toLowerCase();
        User user = null;
        try {
            user = facade.queryUser(username);
        }
        catch(Exception e) {
            return badUsernameOrPassword();
        }
        if(user.getPassword().equals(password)) {
            ActionContext.getActionContext().getSession().setAttribute("USER", username);
            return new ModelAndView("redirect:start.do");
        }
        return badUsernameOrPassword();
    }

    ModelAndView badUsernameOrPassword() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", username);
        map.put("message", "Bad username or password!");
        return new ModelAndView("/signon.html", map);
    }
}
